package com.coocaa.app.lib.cleaner.localapp;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Eric on 2016/8/29.
 */
public class XAppService {
    private static final String MYAPP_CATEGORY = "coocaa.intent.category.MYAPP_DISMISS";
    private static final String APPSTORE_PKG = "com.tianci.appstore";
    private static final String AD_ACTIVITY_ACTION = "coocaa.intent.action.STARTAPP_AD_PRESENTER";
    private static final String APPSTORE_APP = "com.tianci.appstore.appstore";
    private static final String GAMECENTER_APP = "com.tianci.appstore.gamecenter";
    private static final String AD_ACTIVITY_CLASS = "com.coocaa.x.modual.ad.p.StartAppADPresenter";

    public static List<XAppInfo> getLocalApps(Context mContext) {
        List<XAppInfo> ret = new ArrayList<XAppInfo>();
        PackageManager pm = mContext.getPackageManager();
        List<PackageInfo> packages = pm.getInstalledPackages(0);
        for (PackageInfo i : packages) {
            XAppInfo info = packageInfo2AppInfo(i, pm, false);
            if (info != null)
                ret.add(info);
        }
        return ret;
    }

    public static List<XAppInfo> getLocalAppsForMine(Context mContext) {
        List<XAppInfo> ret = new ArrayList<XAppInfo>();
        PackageManager pm = mContext.getPackageManager();
        List<PackageInfo> packages = pm.getInstalledPackages(0);
        for (PackageInfo i : packages) {
            XAppInfo info = packageInfo2AppInfo(i, pm, true);
            if (info != null && info.getLaunchComponents() != null && info.getLaunchComponents().size() > 0)
                ret.add(info);
        }
        return ret;
    }

    public static void startApp(Context mContext, Intent intent, String src) {
        if (isADClassExit(mContext) && needStartWithAD(mContext)) {
            String space = "CCADTV10011";
            String app = APPSTORE_APP;
            String fromPkg = "";
            if (intent != null)
                fromPkg = intent.getPackage();
            Intent adIntent = getIntent(intent, app, space);
            adIntent.putExtra("frompkg", fromPkg);
            adIntent.putExtra("src", src);
            adIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            mContext.startActivity(adIntent);
        } else {
            mContext.startActivity(intent);
        }
    }

    private static boolean needStartWithAD(Context context) {
//        try {
//            long total = SkySystemUtil.getTotalMemory();
//            Log.d("ad", "memory below 512:" + total);
//            if (total < 512) {
//                if (isAppStoreUIThreadExit(context)) {
//                    return true;
//                }
//                return false;
//            }
//            return true;
//        }catch (Exception e){
//            return false;
//        }
        return true;
    }

    private static boolean isAppStoreUIThreadExit(Context context) {
        ActivityManager mActivityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo appProcess : mActivityManager
                .getRunningAppProcesses()) {
            if (appProcess.processName.equals("com.tianci.appstore:appstore")) {
                return true;
            }
        }
        return false;
    }

    private static Intent getIntent(Intent intent, String app, String space) {
        Intent adIntent = new Intent();
        adIntent.setPackage(APPSTORE_PKG);
        adIntent.setAction(AD_ACTIVITY_ACTION);
        adIntent.putExtra("app", app);
        adIntent.putExtra("space", space);
        if (intent != null) {
            Bundle b = new Bundle();
            b.putParcelable("eIntent", intent);
            adIntent.putExtras(b);
        }
        return adIntent;
    }

    private static XAppInfo packageInfo2AppInfo(PackageInfo i, PackageManager pm, boolean filterDisable) {
        if (TextUtils.isEmpty(i.packageName)) {
            Log.e("local", "shit!!! the androidapp packageInfo.packageName is null!!");
            return null;
        }
        XAppInfo info = new XAppInfo();
        info.setPackageName(i.packageName);
        info.setVersionName(i.versionName);
        info.setVersionCode(i.versionCode);
        info.setFlags(i.applicationInfo.flags);
        info.setFirstInstallTime(i.firstInstallTime);
        info.setInstallLocation(i.installLocation);
        if (i.sharedUserId != null && i.sharedUserId.equals("android.uid.system")) {
            info.setSystemUserId(true);
        } else {
            info.setSystemUserId(false);
        }
        info.setLabel(getPackageLabel(info.getPackageName(), pm));
//        info.setIcon(pm.getApplicationIcon(i.applicationInfo));

        info.getLaunchComponents().addAll(getLaunchComponent(i.packageName, pm, filterDisable));
        return info;
    }

    private static List<XLaunchComponent> getLaunchComponent(String packageName, PackageManager pm, boolean filterDisable) {
        List<XLaunchComponent> cns = new ArrayList<XLaunchComponent>();
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.setPackage(packageName);
        List<ResolveInfo> resolveInfo = pm.queryIntentActivities(intent, PackageManager.GET_DISABLED_COMPONENTS
                | PackageManager.GET_RESOLVED_FILTER);
        if (resolveInfo != null && resolveInfo.size() > 0) {
            for (ResolveInfo i : resolveInfo) {
                XLaunchComponent cn = new XLaunchComponent();
                cn.setPackageName(packageName);
                cn.setClassName(i.activityInfo.name);

                if (packageName.equals("com.tianci.movieplatform") || packageName.equals("com.tianci.localmedia"))
                    continue;

                if (filterDisable) {
                    int enable = 0;
                    int app_enable = 0;
                    try {
                        enable = pm.getComponentEnabledSetting(cn.getComponent());
                        app_enable = pm.getApplicationEnabledSetting(cn.getPackageName());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (enable > 1 || app_enable > 1)
                        continue;
                }
                cn.setLabel(getLaunchComponentLabel(cn, pm));

                int catCount = i.filter.countCategories();
                for (int j = 0; j < catCount; j++) {
//                    Log.d("cn"," pkg:"+cn.getClassName()+" category:"+i.filter.getCategory(j));
                    cn.getCategories().add(i.filter.getCategory(j));
                }
                if (filterDisable) {
                    if (cn.containCategory(MYAPP_CATEGORY))
                        continue;
                }
                Log.d("cn", "getLaunchComponent pkg:" + cn.getPackageName() + " class:" + cn.getComponent().getClassName());
                cns.add(cn);
            }
        }
        return cns;
    }

    private static String getPackageLabel(String packageName, PackageManager pm) {
        try {
            ApplicationInfo i = pm.getApplicationInfo(packageName, 0);
            return i.loadLabel(pm).toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return packageName;
    }

    private static String getLaunchComponentLabel(XLaunchComponent cn, PackageManager pm) {
        try {
            ActivityInfo i = pm.getActivityInfo(cn.getComponent(), 0);
            return i.loadLabel(pm).toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            ApplicationInfo i = pm.getApplicationInfo(cn.getPackageName(), 0);
            return i.loadLabel(pm).toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return cn.getComponent().toString();
    }

    public static Drawable getIconByPackage(Context mContext, String pkg) {
        PackageManager pm = mContext.getPackageManager();
        try {
            ApplicationInfo info = pm.getApplicationInfo(pkg, PackageManager.GET_DISABLED_COMPONENTS);
            return pm.getApplicationIcon(info);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Drawable getIconByLaunchComponent(Context mContext, XLaunchComponent cn) {
        Drawable icon = null;
        PackageManager pm = mContext.getPackageManager();

        try {
            ActivityInfo aInfo = pm.getActivityInfo(cn.getComponent(), 0);
            if (aInfo != null)
                icon = aInfo.loadIcon(pm);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (icon == null) {
            try {
                ApplicationInfo info = pm.getApplicationInfo(cn.getPackageName(), PackageManager.GET_DISABLED_COMPONENTS);
                icon = pm.getApplicationIcon(info);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return icon;
    }

    private static boolean isADClassExit(Context context) {
        try {
            PackageManager pm = context.getPackageManager();
            Intent intent = new Intent();
            intent.setAction(AD_ACTIVITY_ACTION);
            intent.setPackage(APPSTORE_PKG);
            List<ResolveInfo> resolveInfo = pm.queryIntentActivities(intent, PackageManager.GET_DISABLED_COMPONENTS
                    | PackageManager.GET_RESOLVED_FILTER);
            if (resolveInfo != null && resolveInfo.size() > 0) {
                for (ResolveInfo i : resolveInfo) {
                    String adClass = i.activityInfo.name;
                    if (adClass.equals(AD_ACTIVITY_CLASS)) {
                        return true;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

}
